/**
 * Created by tanbingqin on 2019/4/25.
 */
import React from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common'
import { Form, Affix, Button, message, Modal, Input } from 'antd';
import LanguageInput from 'components/template/language-input/language-input'
const FormItem = Form.Item;
const {TextArea} = Input;

class OutItineraryModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentData: {
        isShow: true,
        i18n: {}
      }
    }
  }

  componentWillMount() {};

  componentWillReceiveProps(nextProps) {
    const { visible } = this.props;
    if (!visible && nextProps.visible) {
      if (nextProps.selectedIndex > -1) {
        //编辑状态的初始化
        this.setState({
          currentData: JSON.parse(JSON.stringify(nextProps.outList[nextProps.selectedIndex]))
        }, () => {
          const { currentData } = this.state;
          this.props.form.setFieldsValue({
            name: currentData.name,
            code: currentData.code,
            desc: currentData.desc
          });
        });
      } else {
        //新建的初始化
        this.setState({
          currentData: {
            isShow: true,
            i18n: {}
          }
        });
        this.props.form.resetFields();
      }
    }
    //关闭modal后的操作
    if (visible && !nextProps.visible) {
      this.props.form.resetFields();
    }
  };

  handleOk = () => {
    const { currentData } = this.state;
    const { selectedIndex, outList } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        //检验code是否唯一
        let isDuplicate = false; //code是否重复
        outList.map((out, outIndex) => {
          if (out.code === values.code && outIndex !== selectedIndex) {
            isDuplicate = true;
          }
        });
        if (isDuplicate) {
          message.error(messages('setting.key1892')/*行程编码已被使用，请修改。*/);
          return;
        }
        currentData.code = values.code;
        currentData.desc = values.desc;
        this.props.onOk(currentData, selectedIndex);
      }
    });
  };

  handleCancel = () => {
    this.props.onCancel();
  };

  handleLanguageInput = (value, i18n, attr) => {
    let { currentData } = this.state;
    currentData[attr] = value;
    currentData['i18n'][attr] = i18n;
    this.setState({currentData});
  };

  //获取多语言输入框的字符长度
  getInpRule = (num) => {
    const { languageList } = this.props;
    let inpRule = [];
    languageList.map(language => {
      inpRule.push({
        length: num,
        language: language.code.toLowerCase()
      });
    });
    return inpRule;
  };

  render() {
    const { currentData } = this.state;
    const { visible, selectedIndex } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    return (
      <Modal title={messages('setting.key1893')/*外部行程*/}
             visible={visible}
             onOk={this.handleOk}
             onCancel={this.handleCancel}
             width={"600px"}>
        <Form>
          <FormItem {...formItemLayout} label={messages('setting.key1894')/*行程编码*/}>
            {getFieldDecorator('code', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')  //请输入
                },
                {
                  max: 200,
                  message: messages('common.max.characters.length', {max: 200})
                }
              ],
              initialValue: currentData.code ? currentData.code : ''
            })(
              <Input type="text"
                     autoComplete="off"
                     placeholder={messages('common.please.enter')}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1895')/*行程名称*/}>
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')  //请输入
                },
                {
                  max: 200,
                  message: messages('common.max.characters.length', {max: 200})
                }
              ],
              initialValue: ''
            })(
              <LanguageInput nameChange={(value, i18n) => this.handleLanguageInput(value, i18n, 'name')}
                             width={'100%'}
                             name={currentData.name}
                             isEdit
                             inpRule={this.getInpRule(200)}
                             mainLanguageIsRequired={false}
                             placeholder={messages('common.please.enter')}
                             i18nName={currentData.i18n.name}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key597')/*备注*/}>
            {getFieldDecorator('desc', {
              rules: [
                {
                  max: 200,
                  message: messages('common.max.characters.length', {max: 200})
                }
              ],
              initialValue: currentData.desc ? currentData.desc : ''
            })(
              <TextArea rows={4} placeholder={messages('common.please.enter')} style={{resize: 'none'}}/>
            )}
          </FormItem>
        </Form>
      </Modal>
    )
  }
}

OutItineraryModal.propTypes = {
  onCancel: React.PropTypes.func,
  visible: React.PropTypes.bool,  //对话框是否可见
  onOk: React.PropTypes.func,  //点击OK后的回调
  outList: React.PropTypes.array, //外部行程数据列表
  selectedIndex: React.PropTypes.number  //选中的外部行程index
};

function mapStateToProps(state) {
  return {
    languageList: state.login.languageList
  }
}
const wrappedOutItineraryModal = Form.create()(OutItineraryModal);
export default connect(mapStateToProps)(wrappedOutItineraryModal)
